﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.ComponentModel.Composition.Hosting;

namespace WCFMEFSample.Interface
{
    /// <summary>
    /// Providers instance creation through a composition container
    /// </summary>
    public class ExportInstanceProvider:IInstanceProvider
    {
        private readonly string _name;
        private readonly CompositionContainer _container;

        public ExportInstanceProvider(CompositionContainer container,string name)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            
            _container = container;
            _name = name;
        }

        #region IInstanceProvider
        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return _container
                .GetExports<IHostedService, IHostedServiceMetadata>()
                .Where(x => x.Metadata.Name.Equals(_name, StringComparison.OrdinalIgnoreCase))
                .Select(x => x.Value)
                .FirstOrDefault();
        }

        public object GetInstance(InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
            var disposable = instance as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
        #endregion
    }
}
